//
//  LeftMenuView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/30.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  首页左侧菜单
import UIKit
import DynamicBlurView
class LeftMenuView: UIView, UITableViewDelegate, UITableViewDataSource, BottomShadow, AddCornerUIRectCorner, DelayExecution {
    let constellationImageViewSize: CGFloat = 35
    let constellationImageViewRightMargin: CGFloat = 15
    let constellationImageViewTopMargin: CGFloat = 10
    let headerImageViewTopMargin: CGFloat = 15
    let headerImageViewSize: CGFloat = 58
    var tableTap: ((NSInteger) -> Void)?
    let tableProportion: CGFloat = 0.663
    // 暂时不要footer  需要时把上面的0.763 - 0.084，比例按照设计调整就是
    //let footProportion: CGFloat = 0.084
    let headerProportion: CGFloat = 0.335
    var cellHeight: CGFloat = 0
    var headerTap: (() -> Void)?
    let allWidth: CGFloat = ScreenWidth * 0.7
    let allHeight: CGFloat = (ScreenHeight - Ipx(true).bottomMargin - Ipx(true).topMargin) * 0.7
    private let LRMargin: CGFloat = 22.0
    private let images = [""]
    private let titles = ["我的创作", "我的订单", "我的消息", "设置"]
    private let leftImages = ["left_my_creation", "left_my_order", "left_my_message", "left_setting"]
    lazy var showTableView: UITableView = {
        let yPoint: CGFloat = (ScreenHeight - allHeight) / 2
        let tableView = UITableView(frame: CGRect(x: -allWidth, y: yPoint, width: allWidth, height: allHeight))
        cellHeight = allHeight * tableProportion / CGFloat(titles.count)
        tableView.backgroundColor = ONColor.leftViewColor
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "\(LeftMenuTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        addCornerWithView(aView: tableView, aCorners: [.topRight, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        return tableView
    }()
    
    // MARK: - 生命周期
    convenience init(tableTap: @escaping (NSInteger) -> Void, headerTap: @escaping () -> Void) {
        self.init()
        self.tableTap = tableTap
        self.headerTap = headerTap
        setUI()
    }
    
    init() {
        super.init(frame: .zero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUI() {
        self.addSubview(showTableView)
        self.alpha = 0.2
        showTableView.tableHeaderView = setHeaderView(isLogin: MineInfoModel.share.isLogin)
        //showTableView.tableFooterView = setFootView()
    }
    
    // MARK: - 显示和隐藏
    func show() {
        UIApplication.shared.statusBarStyle = .default
        let window = UIApplication.shared.keyWindow
        self.frame = window!.bounds
        self.backgroundColor = ONColor.maskBGColor
        window?.addSubview(self)
        UIView.animate(withDuration: TimeInterval(anTIME)) {
            self.alpha = 1
            self.showTableView.frame.origin.x = 0
        }
    }
    
    func hide() {
        UIApplication.shared.statusBarStyle = .lightContent
        UIView.animate(withDuration: TimeInterval(anTIME), animations: {
            self.showTableView.frame.origin.x = -self.showTableView.width
            self.alpha = 0.5
        }) { (afa) in
            self.removeFromSuperview()
        }
        
    }
    
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? LeftMenuTableViewCell
        cell?.contentLabel.text = titles[indexPath.row]
        cell?.typeImageView.image = UIImage(named: leftImages[indexPath.row])
        cell?.backgroundColor = ONColor.leftViewColor
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    
    // MARK: - tableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        self.tableTap?(indexPath.row)
        hide()
    }
    
    // MARK: - 自定义方法
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touchView = touches.first?.view {
            if touchView.isEqual(self) {
                hide()
            }
        }
    }
    
    // MARK: - 设置tableViewHeader
    func setHeaderView(isLogin: Bool) -> UIView {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: showTableView.width, height: allHeight * headerProportion))
        headerView.backgroundColor = ONColor.leftViewColor
        let bgImageView = UIImageView()
        bgImageView.kf.setImage(with: URL(string: ""))
        bgImageView.clipsToBounds = true
        bgImageView.contentMode = .scaleAspectFill
        
       
        headerView.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(headerView.snp.edges)
        }
        
        if MineInfoModel.share.isLogin {
            let blurView = DynamicBlurView(frame: headerView.bounds)
            blurView.blurRadius = 10
            headerView.insertSubview(blurView, aboveSubview: bgImageView)
            
            let bgView = UIView()
            bgView.backgroundColor = UIColor(hex: 0x000000, alpha: 0.7)
            headerView.addSubview(bgView)
            bgView.snp.makeConstraints { (make) in
                make.edges.equalTo(headerView.snp.edges)
            }
        }
        
       
        
        let constellationImageView = UIImageView()
        headerView.addSubview(constellationImageView)
        constellationImageView.snp.makeConstraints { (make) in
            make.right.equalTo(headerView.snp.right).offset(-constellationImageViewTopMargin)
            make.top.equalTo(headerView.snp.top).offset(constellationImageViewRightMargin)
            make.size.equalTo(CGSize(width: constellationImageViewSize, height: constellationImageViewSize))
        }
        
        // TODO: 假数据到时候删除
//        if let constellationImageName = MineInfoModel.share.userInfModel?.constellationType.rawValue {
//            constellationImageView.image = UIImage(named: constellationImageName)
//        }
        let userInfo:UserInfoModel? = MineInfoModel.share.userInfModel
        
        let imageView = UIImageView()
        let header: String? = userInfo?.headIcon
        if let headU = header {
            let url = URL(string: "\(BaseURL)\(headU)")
            bgImageView.kf.setImage(with: url, placeholder: UIImage(named: "user_occupyin_Avatar"))
        }
        imageView.layer.cornerRadius = headerImageViewSize / 2
        imageView.layer.masksToBounds = true
        imageView.image = UIImage(named: "user_occupyin_Avatar")
        // TODO: 假数据到时候删除
        if let headerUrl = userInfo?.headIcon {
            let url = URL(string: "\(BaseURL)\(headerUrl)")
            imageView.kf.setImage(with: url, placeholder: UIImage(named: "user_occupyin_Avatar"))
        }
        
        imageView.isUserInteractionEnabled = true
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapHeaderImage))
        imageView.addGestureRecognizer(tapGR)
        headerView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(headerView.snp.centerX)
            make.centerY.equalTo(headerView.snp.centerY).offset(-headerImageViewTopMargin)
            make.size.equalTo(CGSize(width: headerImageViewSize, height: headerImageViewSize))
        }
        
        let nameLabel = UILabel()
        nameLabel.text = "登录|注册"
        nameLabel.sizeToFit()
        nameLabel.textColor = UIColor.white
        nameLabel.font = UIFont.systemFont(ofSize: 15)
        headerView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom).offset(5)
            make.centerX.equalTo(imageView.snp.centerX)
        }
        
        // TODO: 假数据到时候删除
        if let name = userInfo?.nickname {
            nameLabel.text = name
        }
        
        let genderImageView = UIImageView(image: UIImage(named: "left_male"), highlightedImage: UIImage(named: "left_female"))
        genderImageView.isHidden = !MineInfoModel.share.isLogin
        headerView.addSubview(genderImageView)
        genderImageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(nameLabel.snp.centerY)
            make.left.equalTo(nameLabel.snp.right).offset(3)
        }
        
        // TODO: 假数据到时候删除
        if let gender:String = MineInfoModel.share.userInfModel?.sexy {
            if gender == "男"{
                genderImageView.image = UIImage(named: "left_male")
            }else{
                genderImageView.image = UIImage(named: "left_female")
            }
        }
        
        let lVLabel = UILabel()
        lVLabel.text = "LV\(0)"
        lVLabel.textColor = UIColor.white
        lVLabel.font = UIFont.systemFont(ofSize: 10)
        lVLabel.textAlignment = .center
        lVLabel.sizeToFit()
        lVLabel.layer.cornerRadius = lVLabel.height / 2
        lVLabel.layer.borderColor = UIColor.white.cgColor
        lVLabel.layer.borderWidth = 1.0
        headerView.addSubview(lVLabel)
        lVLabel.isHidden = !MineInfoModel.share.isLogin
        lVLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(nameLabel.snp.centerX)
            make.top.equalTo(nameLabel.snp.bottom).offset(3)
            make.width.equalTo(lVLabel.width + 10)
        }
        
        // TODO: 假数据到时候删除
        if let level = userInfo?.grade?.gradeCode {
            lVLabel.text = level
            lVLabel.sizeToFit()
            lVLabel.snp.updateConstraints({ (make) in
                make.width.equalTo(lVLabel.width + 10)
            })
        }
        
        let lineView = UIView()
        headerView.addSubview(lineView)
        lineView.backgroundColor = UIColor.black
        lineView.snp.makeConstraints { (make) in
            make.bottom.equalTo(headerView.snp.bottom)
            make.left.equalTo(headerView.snp.left)
            make.right.equalTo(headerView.snp.right)
            make.height.equalTo(2)
        }
        return headerView
    }
      // 暂时不要footer 需要时直接展开注释就ok
//    // MARK: - 设置Footer
//    func setFootView() -> UIView {
//        let footView = UIView()
//        footView.frame = CGRect(x: 0, y: 0, width: showTableView.width, height: allHeight * footProportion)
//        footView.backgroundColor = ONColor.leftViewColor
//        let exitButton = UIButton(type: .custom)
//        exitButton.setImage(UIImage(named: "left_exit"), for: .normal)
//        exitButton.addTarget(self, action: #selector(exitTap), for: .touchUpInside)
//        exitButton.setTitle("退出", for: .normal)
//        exitButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
//        exitButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0)
//        exitButton.frame = footView.bounds
//        exitButton.isHidden = !MineInfoModel.share.isLogin
//        footView.addSubview(exitButton)
//        return footView
//    }
    
    // MARK: - 头像点击
    @objc func tapHeaderImage() {
        self.headerTap?()
        hide()
    }
    
    // MARK: - 退出登录
    @objc func exitTap() {
        MineInfoModel.share.exitLogin()
        hide()
    }
}
